package com.after.saas.file.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ZipUtil;
import com.after.saas.common.exception.BaseException;
import com.after.saas.common.model.vo.FileVO;
import com.after.saas.common.utils.LocalDateUtil;
import com.after.saas.file.utils.CustomerFileUtil;
import org.docx4j.model.datastorage.migration.VariablePrepare;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Description
 * @Classname FileController
 * @Author hjchen
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2023/3/27 8:37
 */
@RestController
@RequestMapping("/docx")
public class FileController {

    @Value("${upload.tomcat.cacheDir}")
    private String cacheDir;

    /**
     * 模板填充并下载
     *
     * @param response
     * @return void
     * @author hjchen
     * @date 2023/3/24 10:24
     **/
    @RequestMapping(value = "/downLoadExcel", method = RequestMethod.GET)
    public void downLoadExcel(HttpServletResponse response) {
        replaceData(response);
    }

    private void replaceData(HttpServletResponse response) {
        Map<String, String> data = new HashMap<>(16);
        data.put("uname", "陈老师");
        data.put("usex", "男");
        data.put("ubirthdate", "1998年10月22日");
        data.put("unation", "汉族");
        data.put("unative", "广东深圳");
        data.put("uplace", "广东汕头");
        data.put("upolity", "团员");
        data.put("uworkdate", "2020年3月16日");
        data.put("uhealth", "良好");
        data.put("umajorpost", "软件开发");
        data.put("umajor", "Java开发");
        data.put("curDate", LocalDateUtil.nowDateStr(""));
        // 照片路径以及大小
        Map<String, Object> phomap = new HashMap<>(8);
        phomap.put("width", 100);
        phomap.put("height", 130);
        phomap.put("type", "png");
        Resource resource = new DefaultResourceLoader().getResource("template/01-个人简历-模板.docx");
        try (ServletOutputStream os = response.getOutputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(Objects.requireNonNull(resource.getFilename()), "UTF-8"));
            //加载模板文件并创建WordprocessingMLPackage对象
            WordprocessingMLPackage wordPackage = WordprocessingMLPackage.load(resource.getInputStream());
            MainDocumentPart documentPart = wordPackage.getMainDocumentPart();
            VariablePrepare.prepare(wordPackage);
            documentPart.variableReplace(data);
            wordPackage.save(outputStream);
            outputStream.writeTo(os);
        } catch (Exception e) {
            throw new BaseException("文件下载异常：" + e.getMessage());
        }
    }

    /**
     * 压缩文件并下载
     *
     * @param response
     * @return void
     * @author hjchen
     * @date 2023/3/24 10:24
     **/
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void download(HttpServletResponse response) {
        List<FileVO> fileList = CustomerFileUtil.getFileList();
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setCharacterEncoding("utf-8");
        File[] files = CustomerFileUtil.creatDirAndRenameFile(fileList);
        String fileName = String.format("测试压缩文件-%s.zip", DateUtil.format(LocalDateTime.now(), DatePattern.NORM_DATE_PATTERN));
        File file = ZipUtil.zip(FileUtil.file(cacheDir + fileName), true, files);
        CustomerFileUtil.del(files);
        try (ServletOutputStream os = response.getOutputStream(); InputStream inputStream = IoUtil.toStream(file)) {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            IoUtil.copy(inputStream, os);
        } catch (Exception e) {
            throw new BaseException("文件下载异常：" + e.getMessage());
        } finally {
            FileUtil.del(file);
        }
    }


}
